import axios from "axios"
import baseUrl from "./config"
import store from "../store"


axios.defaults.timeout = 5000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

//baseUrl
axios.defaults.baseURL = baseUrl;

//http request
axios.interceptors.request.use(
    config => {
        if (store.state.login.login_token) {
            config.headers.authorization = `bearer${store.state.login.login_token}`
        }
        return config
    },
    err => {
        return Promise.reject(err)
    }
)

//http response
axios.interceptors.response.use((res) => {
    return res;
}, err => {
    if (err && err.response) {
        const data = err.response.data;
        if (data.status_code == "401") {
            store.commit("LOGIN_OUT");
        } else if (data.status_code == 400) {
            store.commit("APP_MESSAGE", data.message);
        } else {
            store.commit("APP_MESSAGE", "网络异常");
        }
        return Promise.reject(data)
    }
    return Promise.reject(err)
})

export default function fetch(method = "get", url, params) {
    return new Promise((resolve, reject) => {
        if (method == "get") {
            axios.get(url, {
                    params: params
                })
                .then(response => {
                    resolve(response.data)
                }, err => {
                    reject(err)
                })
                .catch((error) => {
                    reject(error)
                })
        } else {
            axios.post(url, params)
                .then(response => {
                    resolve(response.data);
                }, err => {
                    reject(err);
                })
                .catch((error) => {
                    reject(error)
                })
        }
    })
}